#include "widget.h"
#include "ui_widget.h"
#include "Worker.h"
#include "QDebug"
#include "QPainter"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    InitUartThread();

    m_img = new QImage(IMAGE_WIDTH,IMAGE_HIGHT,QImage::Format_RGB16);
    m_img->fill(Qt::green);
}

Widget::~Widget()
{
    QuitUartThread();
    delete ui;
}

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter paint(this);

    paint.drawImage(QPoint(0,0),*m_img);
}


void Widget::handleResults(quint8 *data,quint32 size)
{
    static quint32 count=0;
//    if((count++%4)!=1)return;
//    qDebug()<<count;
    SetImgColor(data, size);
}

void Widget::InitUartThread()
{
    Worker *worker = new Worker;
    worker->moveToThread(&workerThread);
    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(worker, &Worker::resultReady, this, &Widget::handleResults);
    workerThread.start();
}

void Widget::QuitUartThread()
{
    workerThread.quit();
    workerThread.wait();
}

void Widget::SetImgColor(quint8 *data, quint32 size)
{
    uchar * imgdata = m_img->bits();
    Worker::PixArray *p=Q_NULLPTR;
//    quint32 r,g,b;
//    if(sizeof (Worker::PixArray)==size){
//        qDebug()<<size;

//        p = (Worker::PixArray *)data;

//        for(int i=IMAGE_WIDTH*IMAGE_HIGHT/2;i<IMAGE_WIDTH*IMAGE_HIGHT;i++){
//            r = p->img32Data[i]&0x1F;
//            g = (p->img32Data[i]&0x1C0>>1);
//            b = r|g;
//            r = (p->img32Data[i]>>8)&0x1F00;
//            g = (((p->img32Data[i]>>8)&0x1C000)>>1);
//            p->img16Data[i] = b|g|r;
//        }
//    }
    if(size>IMAGE_WIDTH*IMAGE_HIGHT*2)size=IMAGE_WIDTH*IMAGE_HIGHT*2;
    memcpy(imgdata,data,size);
//    memset(data,0,size);
    update();
}

